package com.dinree.activity;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.fastjson.TypeReference;
import com.base.library.Constant;
import com.base.library.TopBarBaseActivity;
import com.base.library.dialog.BottomDialog;
import com.base.library.http.HttpResult;
import com.base.library.http.upload.FileUploadObserver;
import com.base.library.http.upload.RetrofitClient;
import com.base.library.manager.DialogManager;
import com.base.library.utils.DateUtil;
import com.base.library.utils.JsonUtils;
import com.base.library.utils.StringUtils;
import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.bumptech.glide.Glide;
import com.dinree.R;
import com.dinree.api.UserApi;
import com.dinree.bean.JsonBean;
import com.dinree.bean.UploadBean;
import com.dinree.bean.UserBean;
import com.dinree.databinding.ActivityEditProfileBinding;
import com.dinree.databinding.PhotoDialogBinding;
import com.dinree.databinding.SexDialogBinding;
import com.google.gson.Gson;
import com.jakewharton.rxbinding2.view.RxView;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.LubanOptions;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.model.TakePhotoOptions;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;

import org.json.JSONArray;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import okhttp3.ResponseBody;

import static com.base.library.Constant.WINDOW_DURATION;

public class EditProfileActivity extends TopBarBaseActivity implements TakePhoto.TakeResultListener, InvokeListener {
    private ActivityEditProfileBinding activityEditProfileBinding;
    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private boolean isLoaded = false;
    private TakePhoto takePhoto;
    private InvokeParam invokeParam;
    private String head, nickname, sex, email, birthday, area;
    private int type;
    private String path;
    private MaterialDialog dialog;
    private UserBean userBean;

    @Override
    public int getContentView() {
        return R.layout.activity_edit_profile;
    }

    @Override
    public void initContentView(Bundle savedInstanceState) {
        activityEditProfileBinding = getContentViewBinding();
        userBean = realm.findFirst(UserBean.class);
        mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        setTitle("完善资料");
        setTopLeftButton(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        type = getIntent().getIntExtra("type", 0);
        RxView.clicks(activityEditProfileBinding.btnSubmit).throttleFirst(WINDOW_DURATION, TimeUnit.SECONDS).subscribe(v -> {
            submit();
        });
        RxView.clicks(activityEditProfileBinding.head).throttleFirst(WINDOW_DURATION, TimeUnit.SECONDS).subscribe(v -> {
            showPhoto();
        });
        RxView.clicks(activityEditProfileBinding.sex).throttleFirst(WINDOW_DURATION, TimeUnit.SECONDS).subscribe(v -> {
            showSex();
        });
        RxView.clicks(activityEditProfileBinding.area).throttleFirst(WINDOW_DURATION, TimeUnit.SECONDS).subscribe(v -> {
            showAddress();
        });
        RxView.clicks(activityEditProfileBinding.birthday).throttleFirst(WINDOW_DURATION, TimeUnit.SECONDS).subscribe(v -> {
            showTime();
        });
    }

    private void submit() {
        if (type == 1) {
            Intent intent = new Intent(mContext, MainActivity.class);
            startActivity(intent);
        } else if (type == 2) {
            Intent intent = new Intent(mContext, RefereeActivity.class);
            startActivity(intent);
        }
        nickname = activityEditProfileBinding.nickname.getText();
        email = activityEditProfileBinding.email.getText();
        if (StringUtils.isEmpty(nickname)) {
            showMsg(R.string.hint_nickname);
            return;
        }
        if (StringUtils.isEmpty(email)) {
            showMsg(R.string.hint_email);
            return;
        }
        if (StringUtils.isEmpty(sex)) {
            showMsg(R.string.hint_sex);
            return;
        }
        if (StringUtils.isEmpty(birthday)) {
            showMsg(R.string.hint_birthday);
            return;
        }
        if (StringUtils.isEmpty(area)) {
            showMsg(R.string.hint_area);
            return;
        }
        if (StringUtils.isEmpty(head)) {
            showMsg("请上传头像");
            return;
        }
        dialog = DialogManager.showDefaultProgress(mContext);
        upload();
    }

    private void upload() {
        String url = Constant.HOST + "epsea/public/api/user/upload_file?category=avatar";
        File file = new File(path);
        RetrofitClient.getInstance().upLoadFile(url, file, new FileUploadObserver<ResponseBody>() {
            @Override
            public void onUpLoadSuccess(ResponseBody responseBody) {
                try {
                    if (userBean != null) {
                        HttpResult<UploadBean> httpResult = JsonUtils.getInstance().fromJson(responseBody.string(), new TypeReference<HttpResult<UploadBean>>() {
                        });
                        if (httpResult != null) {
                            if (httpResult.code == 0) {
                                UserApi.getInstance(mContext).saveBasicInfo(userBean.user_id, userBean.user_token, nickname, "", "", email, sex, area, birthday, "", "", "", httpResult.data.url, "", "", "", "").subscribe(s -> {
                                    Intent intent = new Intent(mContext, MainActivity.class);
                                    startActivity(intent);
                                }, e -> {
                                });
                            } else {
                                showMsg("头像上传失败");
                                dialog.dismiss();
                            }
                        } else {
                            showMsg("头像上传失败");
                            dialog.dismiss();
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                dialog.dismiss();
            }

            @Override
            public void onUpLoadFail(Throwable e) {
                showMsg("头像上传失败");
                dialog.dismiss();
            }

            @Override
            public void onProgress(int progress) {
            }
        });
    }

    private void showSex() {
        BottomDialog bottomDialog = new BottomDialog(mContext, R.layout.sex_dialog);
        SexDialogBinding sexDialogBinding = bottomDialog.getViewBinding();
        RxView.clicks(sexDialogBinding.man).throttleFirst(WINDOW_DURATION, TimeUnit.SECONDS).subscribe(v -> {
            sex = "男";
            activityEditProfileBinding.sex.setText(sex);
            bottomDialog.dismiss();
        });
        RxView.clicks(sexDialogBinding.woman).throttleFirst(WINDOW_DURATION, TimeUnit.SECONDS).subscribe(v -> {
            sex = "女";
            activityEditProfileBinding.sex.setText(sex);
            bottomDialog.dismiss();
        });
        RxView.clicks(sexDialogBinding.cancel).throttleFirst(WINDOW_DURATION, TimeUnit.SECONDS).subscribe(v -> {
            bottomDialog.dismiss();
        });

        bottomDialog.show();
    }

    private void showTime() {
        TimePickerView pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                birthday = DateUtil.getStringYMD(date);
                activityEditProfileBinding.birthday.setText(birthday);
            }
        })
                .setSubmitColor(getResources().getColor(R.color.mainColor))
                .setCancelColor(Color.GRAY)
                .setLabel("", "", "", "", "", "")
                .setType(new boolean[]{true, true, true, false, false, false})
                .build();
        pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
        pvTime.show();
    }

    private void showPhoto() {
        BottomDialog bottomDialog = new BottomDialog(mContext, R.layout.photo_dialog);
        PhotoDialogBinding photoDialogBinding = bottomDialog.getViewBinding();
        RxView.clicks(photoDialogBinding.picture).throttleFirst(WINDOW_DURATION, TimeUnit.SECONDS).subscribe(v -> {
//                takePhoto.onPickFromGalleryWithCrop(imageUri,getCropOptions());
            CompressConfig compressConfig = new CompressConfig.Builder().setMaxSize(50 * 1024).setMaxPixel(800).create();
            takePhoto.onEnableCompress(compressConfig, true);
            takePhoto.onPickFromGallery();
            bottomDialog.dismiss();
        });
        RxView.clicks(photoDialogBinding.takePhoto).throttleFirst(WINDOW_DURATION, TimeUnit.SECONDS).subscribe(v -> {
//            takePhoto.onPickFromCaptureWithCrop(imageUri,getCropOptions());
            File file = new File(Environment.getExternalStorageDirectory(), "/head/" + System.currentTimeMillis() + ".jpg");
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            Uri imageUri = Uri.fromFile(file);
            path = file.getAbsolutePath();
            CompressConfig compressConfig = new CompressConfig.Builder().setMaxSize(50 * 1024).setMaxPixel(800).create();
            takePhoto.onEnableCompress(compressConfig, true);
            takePhoto.onPickFromCapture(imageUri);
            bottomDialog.dismiss();
        });
        RxView.clicks(photoDialogBinding.cancel).throttleFirst(WINDOW_DURATION, TimeUnit.SECONDS).subscribe(v -> {
            bottomDialog.dismiss();
        });
        bottomDialog.show();
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 写子线程中的操作,解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;
                case MSG_LOAD_SUCCESS:
                    isLoaded = true;
                    break;
                case MSG_LOAD_FAILED:
                    Toast.makeText(mContext, "获取地区信息失败", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    private void showAddress() {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                area = options1Items.get(options1).getPickerViewText() +
                        options2Items.get(options1).get(options2) +
                        options3Items.get(options1).get(options2).get(options3);
                activityEditProfileBinding.area.setText(area);
            }
        })

                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .setSubmitColor(getResources().getColor(R.color.mainColor))
                .setCancelColor(Color.GRAY)
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new JsonUtils().getJson(this, "province.json");//获取assets目录下的json文件数据

        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市

                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {

                    for (int d = 0; d < jsonBean.get(i).getCityList().get(c).getArea().size(); d++) {//该城市对应地区所有数据
                        String AreaName = jsonBean.get(i).getCityList().get(c).getArea().get(d);

                        City_AreaList.add(AreaName);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }


    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getTakePhoto().onCreate(savedInstanceState);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this);
    }

    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return takePhoto;
    }

    @Override
    public void takeSuccess(TResult result) {
        path = result.getImage().getCompressPath();
        Glide.with(this).load(new File(path)).into(activityEditProfileBinding.imgHead);
    }

    @Override
    public void takeFail(TResult result, String msg) {
        path = null;
    }

    @Override
    public void takeCancel() {
        path = null;
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }

    private void configTakePhotoOption(TakePhoto takePhoto) {
        TakePhotoOptions.Builder builder = new TakePhotoOptions.Builder();
        builder.setWithOwnGallery(true);//使用TakePhoto自带相册
        builder.setCorrectImage(true);//纠正拍照的照片旋转角度：
        takePhoto.setTakePhotoOptions(builder.create());
    }

    private void configCompress(TakePhoto takePhoto) {
        int maxSize = 0;
        int width = 0;
        int height = 0;
        boolean showProgressBar = true;
        boolean enableRawFile = true;//压缩后是否保存原图
        CompressConfig config;
        if (true) {//是否用自带压缩工具
            config = new CompressConfig.Builder()
                    .setMaxSize(maxSize)
                    .setMaxPixel(width >= height ? width : height)
                    .enableReserveRaw(enableRawFile)
                    .create();
        } else {
            LubanOptions option = new LubanOptions.Builder()
                    .setMaxHeight(height)
                    .setMaxWidth(width)
                    .setMaxSize(maxSize)
                    .create();
            config = CompressConfig.ofLuban(option);
            config.enableReserveRaw(enableRawFile);
        }
        takePhoto.onEnableCompress(config, showProgressBar);
    }

    private CropOptions getCropOptions() {
        int height = 0;
        int width = 0;
        boolean withWonCrop = true;
        CropOptions.Builder builder = new CropOptions.Builder();
        builder.setAspectX(width).setAspectY(height);
        builder.setOutputX(width).setOutputY(height);
        builder.setWithOwnCrop(withWonCrop);
        return builder.create();
    }
}

